package com.timk.goserver.server.servlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import com.timk.goserver.server.model.LoginCookie;
import com.timk.goserver.server.model.ServerUserInfo;
import com.timk.goserver.server.services.AbstractServiceServlet;
import com.timk.goserver.server.util.HibernateUtil;

/**
 * Login servlet.
 * @author TKington
 *
 */
public class LoginServlet extends HttpServlet {
	private static final int ONE_MONTH = 60 * 60 * 24 * 30;
	private static Random rand = new Random();
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		if(username == null || password == null)  {
			response.sendRedirect("index.html");
			return;
		}
		
		ServerUserInfo user = ServerUserInfo.findUser(username, null);
		
		try {
			if(user == null || !user.checkPassword(password)) {
				response.sendRedirect("index.html");
				return;
			}
		}
		catch(NoSuchAlgorithmException e) {
			e.printStackTrace(response.getWriter());
			return;
		}
		
		initSession(request, response, username);
		response.sendRedirect("Main.html");
	}

	/**
	 * Creates a valid session for a logged in user
	 * @param request the servlet request
	 * @param response the servlet response
	 * @param username the username
	 */
	public static void initSession(HttpServletRequest request,
			HttpServletResponse response, String username) {
		HttpSession session = request.getSession();
		
		if(!session.isNew()) {
			session.invalidate();
			session = request.getSession();
		}
		
		session.setAttribute("username", username);
		session.setAttribute("version",
				String.valueOf(AbstractServiceServlet.VERSION));
		
		long num = rand.nextLong();

		Session hbSession = HibernateUtil.startTrans();
		LoginCookie loginCookie = new LoginCookie(username,
				AbstractServiceServlet.VERSION, num);
		hbSession.save(loginCookie);
		hbSession.getTransaction().commit();
		
		Cookie cookie = new Cookie("persistLogin", String.valueOf(num));
		cookie.setMaxAge(ONE_MONTH);
		response.addCookie(cookie);
	}
}
